# !/usr/bin/env python
# -*- coding: utf-8 -*-
# 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
#
# 请你将两个数相加，并以相同形式返回一个表示和的链表。
#
# 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。
# 输入：l1 = [2,4,3], l2 = [5,6,4]
# 输出：[7,0,8]
# 解释：342 + 465 = 807.
# 示例 2：
#
# 输入：l1 = [0], l2 = [0]
# 输出：[0]
# 示例 3：
#
# 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
# 输出：[8,9,9,9,0,0,0,1]
#  
#
# 提示：
#
# 每个链表中的节点数在范围 [1, 100] 内
# 0 <= Node.val <= 9
# 题目数据保证列表表示的数字不含前导零
#
# 来源：力扣（LeetCode）
# 链接：https://leetcode.cn/problems/add-two-numbers
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        k = 0
        root = None
        cur_node = None
        while l1 is not None or l2 is not None or k != 0:
            s1 = 0
            s2 = 0
            if l1 is not None:
                s1 = l1.val
                l1 = l1.next
            if l2 is not None:
                s2 = l2.val
                l2 = l2.next
            val = s1 + s2 + k
            k = int(val / 10)
            val = val % 10
            now_node = ListNode(val)
            if root is None:
                root = now_node
            else:
                cur_node.next = now_node
            cur_node = now_node
        return root


def to_node(arr: list) -> ListNode:
    if len(arr) == 0:
        return None
    root = ListNode(arr[0])
    next_node = None
    for i in range(1, len(arr)):
        now_node = ListNode(arr[i])
        if i == 1:
            root.next = now_node
        else:
            next_node.next = now_node
        next_node = now_node
    return root


def to_arr(list_node: ListNode) -> list:
    arr = list()
    if list_node is None:
        return arr
    arr.append(list_node.val)
    tmp = list_node.next
    while tmp is not None:
        arr.append(tmp.val)
        tmp = tmp.next
    return arr


if __name__ == '__main__':
    # l1 = [2, 4, 3]
    # l2 = [5, 6, 4]
    l1 = [9, 9, 9, 9, 9, 9, 9]
    l2 = [9, 9, 9, 9]
    node = to_node(l1)
    # print(to_arr(node))
    sum_node = Solution().addTwoNumbers(to_node(l1), to_node(l2))
    print(to_arr(sum_node))
